package com.itheima.controller;

//import com.itheima.common.MyMetaObjectHandler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.itheima.pojo.Employee;

import com.itheima.pojo.R;
import com.itheima.service.EmployeeService;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeServive;

        @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpServletRequest request){
        log.info("开始登录操作...");

        String password = employee.getPassword();
        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(md5password);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername()).eq(Employee::getPassword,employee.getPassword());
        Employee loginEmp = employeeServive.selectOne(lqw);
        if(loginEmp==null){
            return R.error("对不起,用户名或密码错误...");
        }
        if(loginEmp.getStatus()==0){
            return R.error("对不起,您的账号已被禁用,请联系管理员...");
        }
        HttpSession session = request.getSession();
        session.setAttribute("employee",loginEmp.getId());
        return R.success(loginEmp);

    }
//    @PostMapping(value = "/login")
//    public R login(@RequestBody Employee employee) {
//        log.info("开始登录操作...");
//        String password = employee.getPassword();
//        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());
//        employee.setPassword(md5password);
//
//        if (StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())) {
//            return R.error("用户名或密码为空!");
//        }
//
//        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Employee::getUsername, employee.getUsername());
//        lqw.eq(Employee::getPassword, employee.getPassword());
//        Employee loginEmployee = employeeServive.selectOne(lqw);
//        if (loginEmployee == null) {
//            return R.success("用户名或密码错误!");
//        } else {
//            JwtBuilder jwtBuilder = Jwts.builder(); //获得JWT构造器
//            Map<String, Object> map = new HashMap<>();
//            map.put("username",loginEmployee.getUsername());
//            map.put("empId",loginEmployee.getId());
//            //。。。。。
//    String token = jwtBuilder.setSubject("loginEmployee") //设置主题
//            .setIssuedAt(new Date()) //设置jwt生成时间
//            .setId("1") //设置id为token id
//            .setClaims(map) //载荷部分用户自定义的信息
//            .setExpiration(new Date(System.currentTimeMillis() + 100000)) //设置token有效期 30min
//            .signWith(SignatureAlgorithm.HS256, "123456") //设置token加密方式和密钥
//            .compact(); //生成token字符串
//            loginEmployee.setPassword(token);
//            return R.success(loginEmployee);
//
//}
//
//    }

        @PostMapping("/logout")
    public R logOut(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");

        return R.success("退出成功!");
    }
//    @PostMapping("/logout")
//    public R logOut(HttpServletRequest request) {
////        request.getSession().removeAttribute("employee");
//
//
//        return R.success("退出成功!");
//    }

    @PostMapping
    public R insert(@RequestBody Employee employee, HttpServletRequest request) {

        log.info("开始添加员工信息...");
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        Long loginId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(loginId);
        employee.setUpdateUser(loginId);

        employeeServive.insert(employee);
        return R.success("添加员工成功!");
    }

    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        log.info("开启分页查询:");
        Page<Employee> employeePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeServive.page(employeePage, lqw);
        return R.success(employeePage);
    }

    @PutMapping
    public R update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("修改员工信息");
        employeeServive.update(employee);
        return R.success("修改员工信息成功!");
    }

    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {
        log.info("根据id查询用户");
        Employee employee = employeeServive.selectById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息!");
    }


}
